package com.google.gwt.sample.dynatablerf.server.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class SystemPropertyUtil {
	
	private static final String DB_DRIVER = "database.driver";
	private static final String DB_CONNECTION = "database.url";
	private static final String DB_USER = "database.username";
	private static final String DB_PASSWORD = "database.password";
	
	
	public static String getSystemProperty(String propriedade) throws SQLException, IOException {
		 
		Connection dbConnection = null;
		PreparedStatement preparedStatement = null;
		String valor = null;
		String selectSQL = "SELECT valor FROM SystemProperty WHERE propriedade like ?";
 
		try {
			dbConnection = getDBConnection();
			preparedStatement = dbConnection.prepareStatement(selectSQL);
			preparedStatement.setString(1, propriedade);
 
			// execute select SQL stetement
			ResultSet rs = preparedStatement.executeQuery();
			
			while (rs.next()) {
 
				valor = rs.getString("valor");
 
			}
			rs.close();
 
		} catch (SQLException e) {
 
			System.out.println(e.getMessage());
 
		} finally {
 
			if (preparedStatement != null) {
				preparedStatement.close();
			}
 
			if (dbConnection != null) {
				dbConnection.close();
			}
 
		}
		return valor;
	}
	
	
	private static Connection getDBConnection() throws IOException {
		Properties properties = loadSystemProperties();
		Connection dbConnection = null; 
		try {
 
			Class.forName(properties.getProperty(DB_DRIVER)); 
		} catch (ClassNotFoundException e) { 
			System.out.println(e.getMessage());
 		}
		try {
			dbConnection = DriverManager.getConnection(
					properties.getProperty(DB_CONNECTION), properties.getProperty(DB_USER),properties.getProperty(DB_PASSWORD));
			return dbConnection;
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		return dbConnection;
	}
	
	private static Properties loadSystemProperties() throws IOException {
        FileInputStream propFile =
            new FileInputStream( "src/main/resources/system.properties");
        Properties p =
            new Properties(System.getProperties());
        p.load(propFile);
        return p;
	}
}
